package com.example.forwardmessages

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import java.util.concurrent.TimeUnit

/**
 * 激进后台保活管理器，专门针对MIUI系统设计
 * 实现了多种高级保活策略，提高应用在MIUI系统后台的存活率
 */
object RadicalKeepAliveManager {
    private const val TAG = "RadicalKeepAliveManager"
    private const val NOTIFICATION_CHANNEL_ID = "radical_keep_alive"
    private const val NOTIFICATION_ID = 1001
    private const val REQUEST_CODE = 1002
    
    // 重试参数
    private const val MAX_RETRY_COUNT = 10
    private const val BASE_RETRY_INTERVAL_MS = 2000 // 基础重试间隔2秒
    
    // AlarmManager定时唤醒间隔（毫秒）- 激进模式使用更短的间隔
    private const val ALARM_INTERVAL_MS = 60 * 1000 // 1分钟
    
    // 标志变量
    private var isInitialized = false
    private var wakeLock: PowerManager.WakeLock? = null
    
    /**
     * 初始化激进保活管理器
     */
    fun initialize(context: Context) {
        if (isInitialized) {
            Log.d(TAG, "激进保活管理器已经初始化")
            return
        }
        
        Log.d(TAG, "初始化激进保活管理器...")
        isInitialized = true
        
        // 检查并请求必要的MIUI权限
        if (MIUIPermissionHelper.isMIUI()) {
            Log.d(TAG, "检测到MIUI系统，使用激进保活策略")
            
            // 显示激进模式的权限请求对话框
            MIUIPermissionHelper.requestAllRequiredPermissionsForAggressiveKeepAlive(context)
        }
        
        // 启动主进程服务
        startMainProcessService(context)
        
        // 启动守护进程服务
        startGuardProcessService(context)
        
        // 设置AlarmManager定时唤醒
        setupAlarmManager(context)
        
        // 启动增强版广播接收器
        enableEnhancedBootReceiver(context)
        
        // 获取唤醒锁
        acquireWakeLock(context)
        
        // 启动心跳检测
        startHeartbeat(context)
        
        Log.d(TAG, "激进保活管理器初始化完成")
    }
    
    /**
     * 关闭激进保活管理器
     */
    fun shutdown(context: Context) {
        if (!isInitialized) {
            return
        }
        
        Log.d(TAG, "关闭激进保活管理器...")
        
        // 停止主进程服务
        stopMainProcessService(context)
        
        // 停止守护进程服务
        stopGuardProcessService(context)
        
        // 取消AlarmManager
        cancelAlarmManager(context)
        
        // 释放唤醒锁
        releaseWakeLock()
        
        isInitialized = false
        Log.d(TAG, "激进保活管理器已关闭")
    }
    
    /**
     * 启动主进程服务
     */
    private fun startMainProcessService(context: Context) {
        try {
            val intent = Intent(context, MainProcessService::class.java)
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
            
            Log.d(TAG, "主进程服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "启动主进程服务失败: ${e.message}")
            // 使用智能重试机制
            smartRetry("startMainProcessService", 0) { 
                startMainProcessService(context)
            }
        }
    }
    
    /**
     * 停止主进程服务
     */
    private fun stopMainProcessService(context: Context) {
        try {
            val intent = Intent(context, MainProcessService::class.java)
            context.stopService(intent)
            Log.d(TAG, "主进程服务已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止主进程服务失败: ${e.message}")
        }
    }
    
    /**
     * 启动守护进程服务
     */
    private fun startGuardProcessService(context: Context) {
        try {
            val intent = Intent(context, GuardProcessService::class.java)
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
            
            Log.d(TAG, "守护进程服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "启动守护进程服务失败: ${e.message}")
            // 使用智能重试机制
            smartRetry("startGuardProcessService", 0) { 
                startGuardProcessService(context)
            }
        }
    }
    
    /**
     * 停止守护进程服务
     */
    private fun stopGuardProcessService(context: Context) {
        try {
            val intent = Intent(context, GuardProcessService::class.java)
            context.stopService(intent)
            Log.d(TAG, "守护进程服务已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止守护进程服务失败: ${e.message}")
        }
    }
    
    /**
     * 设置AlarmManager定时唤醒
     */
    private fun setupAlarmManager(context: Context) {
        try {
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val intent = Intent(context, AlarmReceiver::class.java)
            
            // 使用不同的标志以提高可靠性
            val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            } else {
                PendingIntent.FLAG_UPDATE_CURRENT
            }
            
            val pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, flags)
            
            // 设置定时任务，使用setExactAndAllowWhileIdle以在Doze模式下也能唤醒
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(
                    AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + ALARM_INTERVAL_MS,
                    pendingIntent
                )
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(
                    AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + ALARM_INTERVAL_MS,
                    pendingIntent
                )
            } else {
                alarmManager.set(
                    AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + ALARM_INTERVAL_MS,
                    pendingIntent
                )
            }
            
            Log.d(TAG, "AlarmManager已设置，间隔: ${ALARM_INTERVAL_MS}ms")
        } catch (e: Exception) {
            Log.e(TAG, "设置AlarmManager失败: ${e.message}")
            // 使用智能重试机制
            smartRetry("setupAlarmManager", 0) { 
                setupAlarmManager(context)
            }
        }
    }
    
    /**
     * 取消AlarmManager
     */
    private fun cancelAlarmManager(context: Context) {
        try {
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val intent = Intent(context, AlarmReceiver::class.java)
            
            val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            } else {
                PendingIntent.FLAG_UPDATE_CURRENT
            }
            
            val pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, flags)
            alarmManager.cancel(pendingIntent)
            
            Log.d(TAG, "AlarmManager已取消")
        } catch (e: Exception) {
            Log.e(TAG, "取消AlarmManager失败: ${e.message}")
        }
    }
    
    /**
     * 启用增强版广播接收器
     */
    private fun enableEnhancedBootReceiver(context: Context) {
        try {
            val pm = context.packageManager
            val componentName = ComponentName(context, EnhancedBootReceiver::class.java)
            
            pm.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            Log.d(TAG, "增强版广播接收器已启用")
        } catch (e: Exception) {
            Log.e(TAG, "启用增强版广播接收器失败: ${e.message}")
        }
    }
    
    /**
     * 获取唤醒锁
     */
    private fun acquireWakeLock(context: Context) {
        try {
            val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
            wakeLock = powerManager.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK, 
                "ForwardMessages:RadicalKeepAlive"
            )
            
            if (wakeLock?.isHeld == false) {
                wakeLock?.acquire(TimeUnit.HOURS.toMillis(1))
                Log.d(TAG, "唤醒锁已获取")
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取唤醒锁失败: ${e.message}")
        }
    }
    
    /**
     * 释放唤醒锁
     */
    private fun releaseWakeLock() {
        try {
            if (wakeLock?.isHeld == true) {
                wakeLock?.release()
                wakeLock = null
                Log.d(TAG, "唤醒锁已释放")
            }
        } catch (e: Exception) {
            Log.e(TAG, "释放唤醒锁失败: ${e.message}")
        }
    }
    
    /**
     * 启动心跳检测
     */
    private fun startHeartbeat(context: Context) {
        val handler = Handler(Looper.getMainLooper())
        val heartbeatRunnable = object : Runnable {
            override fun run() {
                try {
                    // 检查服务是否在运行，如果不在则重启
                    if (!isServiceRunning(context, MainProcessService::class.java.name)) {
                        Log.d(TAG, "主进程服务未在运行，尝试重启")
                        startMainProcessService(context)
                    }
                    
                    if (!isServiceRunning(context, GuardProcessService::class.java.name)) {
                        Log.d(TAG, "守护进程服务未在运行，尝试重启")
                        startGuardProcessService(context)
                    }
                    
                    // 重新获取唤醒锁
                    acquireWakeLock(context)
                    
                    // 重新设置AlarmManager
                    setupAlarmManager(context)
                } catch (e: Exception) {
                    Log.e(TAG, "心跳检测失败: ${e.message}")
                }
                
                // 5分钟后再次检查
                handler.postDelayed(this, TimeUnit.MINUTES.toMillis(5))
            }
        }
        
        // 立即执行一次，然后每5分钟执行一次
        handler.post(heartbeatRunnable)
        Log.d(TAG, "心跳检测已启动")
    }
    
    /**
     * 智能重试机制
     */
    private fun smartRetry(actionName: String, retryCount: Int, action: () -> Unit) {
        if (retryCount >= MAX_RETRY_COUNT) {
            Log.e(TAG, "$actionName 达到最大重试次数 $MAX_RETRY_COUNT，放弃重试")
            return
        }
        
        // 计算指数退避的延迟时间 - 修复：确保结果为Long类型
        val delayMs = BASE_RETRY_INTERVAL_MS.toLong() * (1 shl retryCount)
        Log.d(TAG, "$actionName 将在 ${delayMs}ms 后重试，当前重试次数: ${retryCount + 1}")
        
        val handler = Handler(Looper.getMainLooper())
        handler.postDelayed({
            try {
                action()
            } catch (e: Exception) {
                Log.e(TAG, "$actionName 重试失败: ${e.message}")
                // 继续重试
                smartRetry(actionName, retryCount + 1, action)
            }
        }, delayMs)
    }
    
    /**
     * 检查服务是否在运行
     */
    private fun isServiceRunning(context: Context, serviceClassName: String): Boolean {
        try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val runningServices = activityManager.getRunningServices(Integer.MAX_VALUE)
            
            for (service in runningServices) {
                if (serviceClassName == service.service.className) {
                    return true
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "检查服务运行状态失败: ${e.message}")
        }
        
        return false
    }
    
    /**
     * 主进程服务
     */
    class MainProcessService : android.app.Service() {
        override fun onBind(intent: Intent?): android.os.IBinder? {
            return null
        }
        
        override fun onCreate() {
            super.onCreate()
            Log.d(TAG, "主进程服务 onCreate")
            
            // 创建前台服务通知
            createNotificationChannel(this)
            val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle("应用保持运行中")
                .setContentText("确保消息能够及时接收和处理")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setPriority(NotificationCompat.PRIORITY_MIN)
                .setOngoing(true) // 不可取消
                .setVisibility(NotificationCompat.VISIBILITY_SECRET) // 锁屏时隐藏
                .build()
            
            // 启动前台服务
            startForeground(NOTIFICATION_ID, notification)
        }
        
        override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
            Log.d(TAG, "主进程服务 onStartCommand")
            
            // 监听守护进程服务状态
            val handler = Handler(Looper.getMainLooper())
            handler.postDelayed({
                if (!isServiceRunning(this, GuardProcessService::class.java.name)) {
                    Log.d(TAG, "检测到守护进程服务未在运行，尝试重启")
                    startGuardProcessService(this)
                }
            }, TimeUnit.SECONDS.toMillis(30))
            
            return android.app.Service.START_STICKY
        }
        
        override fun onDestroy() {
            super.onDestroy()
            Log.d(TAG, "主进程服务 onDestroy")
            
            // 服务被销毁时尝试重启
            try {
                val intent = Intent(this, MainProcessService::class.java)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(intent)
                } else {
                    startService(intent)
                }
            } catch (e: Exception) {
                Log.e(TAG, "主进程服务销毁时重启失败: ${e.message}")
            }
        }
        
        private fun createNotificationChannel(context: Context) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = android.app.NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    "应用保持服务",
                    android.app.NotificationManager.IMPORTANCE_MIN
                )
                channel.description = "用于保持应用在后台稳定运行"
                channel.setSound(null, null) // 关闭通知声音
                channel.enableVibration(false) // 关闭振动
                
                val notificationManager = context.getSystemService(android.app.NotificationManager::class.java)
                notificationManager?.createNotificationChannel(channel)
            }
        }
    }
    
    /**
     * 守护进程服务
     */
    class GuardProcessService : android.app.Service() {
        override fun onBind(intent: Intent?): android.os.IBinder? {
            return null
        }
        
        override fun onCreate() {
            super.onCreate()
            Log.d(TAG, "守护进程服务 onCreate")
            
            // 创建前台服务通知
            val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle("应用服务")
                .setContentText("后台服务运行中")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setPriority(NotificationCompat.PRIORITY_MIN)
                .setOngoing(true) // 不可取消
                .setVisibility(NotificationCompat.VISIBILITY_SECRET) // 锁屏时隐藏
                .build()
            
            // 启动前台服务
            startForeground(NOTIFICATION_ID + 1, notification)
        }
        
        override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
            Log.d(TAG, "守护进程服务 onStartCommand")
            
            // 监听主进程服务状态
            val handler = Handler(Looper.getMainLooper())
            handler.postDelayed({
                if (!isServiceRunning(this, MainProcessService::class.java.name)) {
                    Log.d(TAG, "检测到主进程服务未在运行，尝试重启")
                    startMainProcessService(this)
                }
            }, TimeUnit.SECONDS.toMillis(30))
            
            return android.app.Service.START_STICKY
        }
        
        override fun onDestroy() {
            super.onDestroy()
            Log.d(TAG, "守护进程服务 onDestroy")
            
            // 服务被销毁时尝试重启
            try {
                val intent = Intent(this, GuardProcessService::class.java)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(intent)
                } else {
                    startService(intent)
                }
            } catch (e: Exception) {
                Log.e(TAG, "守护进程服务销毁时重启失败: ${e.message}")
            }
        }
    }
    
    /**
     * 定时唤醒广播接收器
     */
    class AlarmReceiver : android.content.BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (context == null) {
                return
            }
            
            Log.d(TAG, "AlarmReceiver 接收到广播")
            
            // 重新设置AlarmManager
            setupAlarmManager(context)
            
            // 检查并启动服务
            if (!isServiceRunning(context, MainProcessService::class.java.name)) {
                Log.d(TAG, "AlarmReceiver: 主进程服务未在运行，尝试重启")
                startMainProcessService(context)
            }
            
            if (!isServiceRunning(context, GuardProcessService::class.java.name)) {
                Log.d(TAG, "AlarmReceiver: 守护进程服务未在运行，尝试重启")
                startGuardProcessService(context)
            }
            
            // 获取唤醒锁
            acquireWakeLock(context)
            
            // 尝试启动应用的EmptyActivity来唤醒进程
            try {
                val emptyIntent = Intent(context, EmptyActivity::class.java)
                emptyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                context.startActivity(emptyIntent)
            } catch (e: Exception) {
                Log.e(TAG, "AlarmReceiver 启动EmptyActivity失败: ${e.message}")
            }
        }
    }
    
    /**
     * 增强版开机广播接收器
     */
    class EnhancedBootReceiver : android.content.BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (context == null || intent == null) {
                return
            }
            
            val action = intent.action
            Log.d(TAG, "EnhancedBootReceiver 接收到广播: $action")
            
            // 针对不同的系统广播采取不同的策略
            when {
                action?.contains("BOOT_COMPLETED") == true -> {
                    // 开机广播，延迟启动以避免被系统杀死
                    val delay = if (MIUIPermissionHelper.isMIUI()) {
                        8000L // MIUI系统延迟8秒（修复：将Int改为Long）
                    } else {
                        3000L // 其他系统延迟3秒（修复：将Int改为Long）
                    }
                    
                    Handler(Looper.getMainLooper()).postDelayed({
                        startMainProcessService(context)
                        startGuardProcessService(context)
                    }, delay)
                }
                
                action?.contains("SCREEN_OFF") == true -> {
                    // 屏幕关闭广播，增加保活强度
                    acquireWakeLock(context)
                    setupAlarmManager(context)
                }
                
                action?.contains("SCREEN_ON") == true -> {
                    // 屏幕开启广播，重新检查服务状态
                    if (!isServiceRunning(context, MainProcessService::class.java.name)) {
                        startMainProcessService(context)
                    }
                    if (!isServiceRunning(context, GuardProcessService::class.java.name)) {
                        startGuardProcessService(context)
                    }
                }
                
                action?.contains("CONNECTIVITY_CHANGE") == true || 
                action?.contains("WIFI_STATE_CHANGE") == true -> {
                    // 网络变化广播，检查服务状态
                    if (!isServiceRunning(context, MainProcessService::class.java.name)) {
                        startMainProcessService(context)
                    }
                }
                
                else -> {
                    // 其他广播，简单检查服务状态
                    Handler(Looper.getMainLooper()).postDelayed({
                        if (!isServiceRunning(context, MainProcessService::class.java.name)) {
                            startMainProcessService(context)
                        }
                    }, 1000)
                }
            }
        }
    }
}